package mtons.cast.modules.play;

import mtons.cast.modules.log.Printer;
import mtons.cast.modules.play.maker.Maker;
import mtons.cast.modules.play.maker.provider.B365Provider;
import mtons.cast.modules.play.ticket.Ticket;
import mtons.cast.modules.play.ticket.strategy.FFCTicketStrategy;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Timer;

/**
 * 游戏客户端
 *
 * Created by langhsu on 2017/10/13.
 */
@Component
public class PlayClient implements ApplicationContextAware {
    private ApplicationContext applicationContext;

    /**
     * 服务器提供商
     */
    private Maker maker;

    /**
     * 出票策略
     */
    private Ticket ticket;

    /**
     * 定时器
     */
    private Timer timer;

    /**
     * 登录状态
     */
    private boolean login;

    @PostConstruct
    public void init() {
        maker = new B365Provider();
        ticket = new FFCTicketStrategy();

        Printer.applicationContext = applicationContext;
    }

    /**
     * 开始
     */
    public String start() {
        if (!login) {
            return "未登录";
        }

        if (timer != null) {
            timer.cancel();
        }
        timer = new Timer();

        Calendar day = Calendar.getInstance();
        day.set(Calendar.SECOND, 40);
        day.add(Calendar.MINUTE, 1);
        WorkTask task = new WorkTask(maker, ticket);
        timer.schedule(task, day.getTime() , 60 * 1000);
        return "主程序将在: " + DateFormatUtils.format(day.getTime(), "HH:mm:ss") + " 执行";
    }

    /**
     * 关闭
     */
    public void stop() {
        timer.cancel();
        timer = null;
    }

    public Maker getMaker() {
        return maker;
    }

    public void setMaker(Maker maker) {
        this.maker = maker;
    }

    public Ticket getTicket() {
        return ticket;
    }

    public void setTicket(Ticket ticket) {
        this.ticket = ticket;
    }

    public boolean isLogin() {
        return login;
    }

    public void setLogin(boolean login) {
        this.login = login;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
